下方是官方給出的 proxyBeanMethod 註解
- Specify whether @Bean methods should get proxied in order to enforce bean lifecycle behavior, e.g. to return shared singleton bean instances even in case of direct @Bean method calls in user code . This feature requires method interception, implemented through a runtime-generated CGLIB subclass which comes with limitations such as the configuration class and its methods not being allowed to declare final.
The default is true, allowing for 'inter-bean references' within the configuration class as well as for external calls to this configuration's @Bean methods, e.g. from another configuration class. If this is not needed since each of this particular configuration's @Bean methods is self-contained and designed as a plain factory method for container use, switch this flag to false in order to avoid CGLIB subclass processing.
Turning off bean method interception effectively processes @Bean methods individually like when declared on non-@Configuration classes, a.k.a. "@Bean Lite Mode" (see @Bean's javadoc). It is therefore behaviorally equivalent to removing the @Configuration stereotype.
什麼是代理 ?
在設計模式之中有一個代理模式,不直接使用物件或是資源本身,而是透過一個代理物件( 有者原本物件的特性) 去間接操作資源。那這個設計模式有什麼用途嗎 ?
其中有一個用途是,代理物件有者原本資源的特性,除此之外我們還可以在這個代理物件,新增新的屬性或是方法,在不修改原本物件的情況下,來增加新功能。這…..好像哪裡聽過 ?
這不是 Spring AOP 在做的事情嗎? AOP 確實是代理的一種應用。
代理的實作方式 ?
代理的實作方式有兩種,一個是透過 JDK 另一個是透過開源專案CGLIB ,這兩者最主要的不同是,前者必須透過一層介面,而後者則是透過繼承的方式去實現代理,在Spring framework 之中,是採用 CGLIB 的方式。
proxyBeanMethod=false 的情況下,@Configuration 標注的類別下的 @Bean Method 就不會被代理,
如果多次呼叫 @Bean Method 就會產生多個實體,這就是 Bean Lite Mode(可參考下方的{官方}Annotation Bean)。
另外在 proxyBeanMethod 的註解之中,有寫到如果 @Bean Method寫在非 @Configuration 類別,同樣會產生
Bean Lite Mode 。
參考資料
{官方} Annotation Bean
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html
https://cloud.tencent.com/developer/article/1838046